package com.zimmor.mq.rocket_train.base;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @Author:zimmor
 * @Date: 2023/2/10 16:25
 * @Description 普通异步消息发送
 * @version: 1.0.0
 */

public class AsyncProducer {
    public static void main(String[] args) throws MQClientException {
        //创建producer
        DefaultMQProducer producer2 = new DefaultMQProducer("producer-group2");
        //设置namesrv
        producer2.setNamesrvAddr("192.168.204.136:9876;192.168.204.137:9876");
        //启动producer
        producer2.start();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            //构建message
            Message message = new Message("base2", "tag2", ("async-message"+i).getBytes());
            try {
                //异步发送消息
                producer2.send(message, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.println(sendResult.toString());
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        System.out.println(throwable);
                    }
                });
            } catch (RemotingException e) {
                e.printStackTrace();
                //发送失败时处理业务
            } catch (InterruptedException e) {
                e.printStackTrace();
                //发送失败时处理业务
            }
        }
        //关闭producer
//        producer2.shutdown();
    }
}
